<template>
  <div class="document-detail">
    <div class="header">
      <el-button @click="$emit('back')" class="back-button">
        <el-icon class="el-icon">
          <ArrowLeft />
        </el-icon>
        返回
      </el-button>
      <h1 class="page-title">{{ record?.title || '文档详情' }}</h1>
      <div class="header-actions">
        <el-button type="success" @click="handleExport" class="export-button">
          <el-icon class="el-icon">
            <Download />
          </el-icon>
          导出
        </el-button>
      </div>
    </div>
    
    <div class="content">

      <div class="segments-section">
        <div class="section-header">
          <h3>文段列表</h3>
          <div class="header-controls">
            <el-input
              v-model="searchText"
              placeholder="搜索文段..."
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <el-empty 
          v-if="!loading && filteredSegments.length === 0" 
          description="暂无文段"
          class="empty-state"
        />

        <div v-if="loading && filteredSegments.length === 0" class="loading-container">
          <div class="loading-spinner">
            <div class="spinner-circle"></div>
            <div class="spinner-circle"></div>
            <div class="spinner-circle"></div>
          </div>
          <span class="loading-text">加载中...</span>
        </div>

        <div v-else class="segments-list">
          <div v-for="(segment) in filteredSegments" 
               :key="segment.id" 
               class="segment-item"
               @click="handleEditSegment(segment)">
            <div class="segment-content">
              <div class="segment-header">
                <h4 class="segment-title">{{ segment.title }}</h4>
                <div class="segment-meta">
                </div>
              </div>
              <p class="segment-preview">
                {{ getSegmentPreview(segment.content) }}
              </p>
            </div>
            <div class="segment-actions">
              <el-button 
                type="danger" 
                link
                @click.stop="handleDeleteSegment(segment)"
                class="action-button"
              >
                <el-icon class="el-icon">
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Download, 
  Document, 
  EditPen, 
  Search, 
  Edit, 
  Delete 
} from '@element-plus/icons-vue'
import { deleteMemory, getDocumentSegments } from '@/api/document'

export default {
  name: 'DocumentDetailPage',
  props: {
    record: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['back', 'edit-segment'],
  setup(props, { emit }) {
    const segments = ref([])
    const loading = ref(false)
    const searchText = ref('')

    const filteredSegments = computed(() => {
      let result = [...segments.value]
      if (searchText.value) {
        result = result.filter(segment => 
          segment.content?.toLowerCase().includes(searchText.value.toLowerCase())
        )
      }
      return result
    })

    // 用props传递的segments
    const fetchSegments = async () => {
      loading.value = true
      try {
        if (props.record?.title) {
          const res = await getDocumentSegments(props.record.title)
          if (res.data && Array.isArray(res.data.data)) {
            segments.value = res.data.data
          } else {
            segments.value = []
          }
        } else {
          segments.value = props.record?.segments ? [...props.record.segments] : []
        }
      } catch (e) {
        segments.value = []
      }
      loading.value = false
    }

    const handleEditSegment = (segment) => {
      emit('edit-segment', {
        ...segment,
        segmentList: segments.value,
        currentIndex: segments.value.findIndex(s => s.id === segment.id),
        totalCount: segments.value.length,
        documentTitle: props.record.title
      })
    }

    const handleDeleteSegment = async (segment) => {
      await ElMessageBox.confirm('确定要删除这个文段吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      try {
        await deleteMemory(segment.id)
        const idx = segments.value.findIndex(s => s.id === segment.id)
        if (idx !== -1) segments.value.splice(idx, 1)
        if (props.record?.segments) {
          const ridx = props.record.segments.findIndex(s => s.id === segment.id)
          if (ridx !== -1) props.record.segments.splice(ridx, 1)
        }
        ElMessage.success('删除成功')
      } catch (e) {
        ElMessage.error('删除失败')
      }
    }

    const handleExport = async () => {
      await new Promise(r => setTimeout(r, 500))
      ElMessage.success('导出功能（假）')
    }

    const handleSearch = () => {}
    const getSegmentPreview = (content) => {
      if (!content) return ''
      return content.length > 100 ? content.substring(0, 100) + '...' : content
    }
    const formatTime = (time) => time ? new Date(time).toLocaleString() : ''
    const formatFileSize = (bytes) => {
      if (!bytes) return ''
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    watch(() => props.record?.id, (newVal) => {
      if (newVal) fetchSegments()
    }, { immediate: true })
    onMounted(() => {
      // console.log('测试测试',props.record.title)
      // if (props.record?.title) fetchSegments()
    })
    return {
      segments,
      loading,
      searchText,
      filteredSegments,
      handleEditSegment,
      handleDeleteSegment,
      handleExport,
      handleSearch,
      getSegmentPreview,
      formatTime,
      formatFileSize
    }
  }
}
</script>

<style scoped>
.document-detail {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
  flex: 1;
  text-align: center;
}

.back-button {
  padding: 8px 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  transform: translateX(-2px);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.export-button {
  padding: 8px 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.export-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.document-info {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.value {
  color: #1a1a1a;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.value.file {
  color: #67c23a;
}

.value.text {
  color: #e6a23c;
}

.segments-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.section-header h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
  white-space: nowrap;
}

.header-controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex: 1;
  max-width: 400px;
}

.search-input {
  flex: 1;
}

.search-input :deep(.el-input__wrapper) {
  background-color: #f5f7fa;
  box-shadow: none !important;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 0 12px;
  height: 36px;
}

.search-input :deep(.el-input__wrapper:hover) {
  background-color: #fff;
  border-color: #c0c4cc;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  background-color: #fff;
  border-color: #409EFF;
  box-shadow: 0 0 0 1px #409EFF !important;
}

.search-input :deep(.el-input__inner) {
  height: 36px;
  font-size: 14px;
}

.search-icon {
  font-size: 16px;
  color: #909399;
}

.empty-state {
  padding: 48px;
  text-align: center;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px;
}

.loading-spinner {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.spinner-circle {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #409EFF;
  animation: bounce 0.5s ease-in-out infinite;
}

.spinner-circle:nth-child(2) {
  animation-delay: 0.1s;
}

.spinner-circle:nth-child(3) {
  animation-delay: 0.2s;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.loading-text {
  color: #909399;
  font-size: 14px;
}

.segments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.segment-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.segment-item:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

.segment-content {
  flex: 1;
  padding-right: 20px;
}

.segment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.segment-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.segment-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.segment-length,
.segment-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.segment-preview {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.segment-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .document-detail {
    padding: 0px;
  }

  .header {
    padding: 12px 16px;
    margin-bottom: 16px;
    flex-direction: column;
    gap: 12px;
  }

  .page-title {
    font-size: 1.2rem;
  }

  .header-actions {
    width: 100%;
    justify-content: center;
  }

  .document-info {
    padding: 16px;
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .segments-section {
    padding: 16px;
  }

  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .header-controls {
    max-width: none;
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }

  .segment-item {
    padding: 16px;
  }

  .segment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .segment-meta {
    gap: 8px;
  }

  .action-button span {
    display: none;
  }
}
</style> 